﻿using InfluxDB.Client.Api.Domain;
using IoTClient;
using IotClientService.Models.Lg;
using IotClientService.Models.Lg.Remote;
using IotClientService.Services;
using IotContract.Enums;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XT.Common.Extensions;

namespace IotClientService.Handles.lgs;
/// <summary>
/// 充氦打钉机
/// </summary>
public class LgHandleNailing : LgHandleBase
{
    public LgHandleNailing(ILgApiService lgCallApiService) : base(lgCallApiService)
    {
    }

    /// <summary>
    /// 设备类型
    /// </summary>
    public override IotEquipType EquipType { get; set; } = IotEquipType.NAIL;
    /// <summary>
    /// 处理消息
    /// </summary>
    /// <param name="msg"></param>
    /// <returns></returns>
    /// <exception cref="NotImplementedException"></exception>
    public override async Task<bool> HandleMsg(LgMsgInfo msg)
    {
        string replyCmd = string.Empty;
        switch (msg.Command)
        {
            // 作业实处理Data报告
            case "901":
                replyCmd = "902";
                await Handle901(msg, replyCmd);
                break;

            // 设备状态报告指示回应
            case "910":
                await Handle910(msg, "910");
                // send 833 

                break;
            // 设备状态报告
            case "913":
                await Handle913(msg, "913");

                break;
            // 作业mode报告
            case "917":
                replyCmd = "918";
                await Handle917(msg, replyCmd);
                break;
            // 通信状态报告邀请
            case "925":
                replyCmd = "926";
                await Handle925(msg, replyCmd);
                break;
            // 通信状态报告回应
            case "926":
                await Handle926(msg, "926");
                break;
            // 电芯投入报告
            case "933":
                replyCmd = "934";
                await Handle933(msg, replyCmd);
                break;

            // 未知命令,错误
            case "981":
                await Handle981(msg, "981");
                break;
            // 设备Trouble报告
            case "985":
                await Handle985(msg, "985");
                break;


            // 设置时间指示
            case "999":
                await Handle999(msg, "999");
                break;
            default:
                // send 981,
                await  Handle981(msg, "981");
                break;
        }
        return true;
    }
    /// <summary>
    /// 作业实处理Data报告
    /// </summary>
    /// <param name="msg"></param>
    /// <param name="replyCmd"></param>
    private async Task Handle901(LgMsgInfo msg, string replyCmd)
    {
        var sendMsg = new LgMsgInfo
        {
            Direction = 0,
            ObjID = msg.ObjID,
            HasMsg = 0,
            SeqNo = msg.SeqNo,
            Command = replyCmd,

        };

        // 1 cellid  24
        string cellId = msg.Message.Substring(18, 24);
        // ng判定  0:ok 1:ng
        string ngCharge = msg.Message.Substring(42, 1);
        // ng code
        string ngCode = msg.Message.Substring(43, 4);
        // 结果数据  实际87
        string result = msg.Message.Substring(47, 87);

        LgNailResult lgNailResult = new LgNailResult
        {

            VacuumValue1 = result.Substring(0, 5).To<double>(),
            VacuumJudgementResult1 = result.Substring(5, 1).To<int>(),
            VacuumValue2 = result.Substring(6, 5).To<double>(),
            VacuumJudgementResult2 = result.Substring(11, 1).To<int>(),
            VacuumValue3 = result.Substring(12, 5).To<double>(),
            VacuumJudgementResult3 = result.Substring(17, 1).To<int>(),
            HeliumPressureValue = result.Substring(18, 5).To<double>(),
            HeliumPressureJudgementResult = result.Substring(23, 1).To<int>(),
            PressureValue = result.Substring(24, 5).To<double>(),
            HoldingTime1 = result.Substring(29, 3).To<double>(),
            HoldingTime2 = result.Substring(32, 3).To<double>(),
            HoldingTime3 = result.Substring(35, 3).To<double>(),
            HeightDifferenceValue = result.Substring(38, 5).To<double>(),
            FeedTime = DateTime.ParseExact(result.Substring(43, 14), "yyyyMMddHHmmss", CultureInfo.InvariantCulture).ToString("yyyy-MM-dd HH:mm:ss"),
            DischargeTime = DateTime.ParseExact(result.Substring(57, 14), "yyyyMMddHHmmss", CultureInfo.InvariantCulture).ToString("yyyy-MM-dd HH:mm:ss"),
            Weight = result.Substring(71, 7).To<double>(),
            LeakageVolume = result.Substring(78, 7).To<double>(),
            WeighingPosition = result.Substring(85, 1).To<int>(),
            NailingPlatform = result.Substring(86, 1).To<int>()

        };


        var rep = await Api.CommitNailingResult(new LgNailingResultRequest
        {
            Cell = cellId,
            Ng = ngCharge.To<int>(),
            NgCode = ngCode,
            Data = lgNailResult,
            EquipNum = Equip.Num,
            EquipType = this.EquipType,
            ProgramType = Equip.ProgramType
        });
        // 0:ok 1:ng
        var ret = 0;
        if (!rep.Success)
        {
            Equip.ExMessage = rep.Message;
            ret = 1;
        }
        else
        {
            ret = rep.Result?.Ret ?? 1;
        }
        if (ret == 1)
        {
            msg.Body = ret.ToString();
            await Handle981(msg, "981");
            return;
        }
        // 24长度
        var cellid = cellId.PadRight(24, ' ');
        var ng = rep.Result?.NgCodes?.FirstOrDefault() ?? "0000";
       
        sendMsg.Body = $"{cellid}{ret}{ng}";
        sendMsg.IsSend = true;
                
        InvokeSend(sendMsg);
    }


    /// <summary>
    /// 电芯投入报告
    /// </summary>
    /// <param name="msg"></param>
    /// <param name="replyCmd"></param>
    private async Task Handle933(LgMsgInfo msg, string replyCmd)
    {
        var sendMsg = new LgMsgInfo
        {
            Direction = 0,
            ObjID = msg.ObjID,
            HasMsg = 0,
            SeqNo = msg.SeqNo,
            Command = replyCmd,
            BoxId   = 9,
        };
        // 电芯ID
        var cellid = msg.Message.Substring(18,24);
        
        Equip.Remark = $"cell load:{cellid}";
        
        var rep = await Api.CommitNailingEnter(new Models.Lg.Remote.LgCellEnterRequest
        {
            Cell = cellid,
            EquipNum = Equip.Num,
            EquipType = this.EquipType,
            ProgramType = Equip.ProgramType
        });
        // 0:ok 1:ng 
        int ret = 0;
        if (!rep.Success)
        {
            Equip.ExMessage = rep.Message;
            ret = 1;
        }
        else
        {
            ret = rep.Result?.Ret ?? 1;
        }
        if (ret == 1)
        {
            msg.Body = ret.ToString();
            await Handle981(msg, "981");
            return;
        }
        #region 传输body


        var cell = cellid;
       
        var ngCode = (rep.Result?.NgCodes?.FirstOrDefault() ?? "0000").PadLeft(4, '0');


        // 电池判定条件 42
        var nailJudge = rep.Result?.ToString();
        // 一次注液最终重量 7
        var total = rep.Result?.Total.ToString().PadLeft(7, '0'); 

        #endregion
        sendMsg.Body = $"{cell}{ret}{ngCode}{nailJudge}{total}";
        sendMsg.IsSend = true;

        InvokeSend(sendMsg);
    }

  



}
